﻿using System;
using System.Drawing;
using System.IO;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Media.Imaging;
using NewProcessGuarder.core;
using NewProcessGuarder.toolFunc;
using System.ComponentModel;
using Telerik.Windows.Controls;
using System.Windows.Media;

namespace NewProcessGuarder
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class XiaorsGuarder : Window, INotifyPropertyChanged
    {

        NotifyIcon notifyIcon;

        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(string keyName) {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(keyName));
            }
        }

        private Guarders guarders;

        public Guarders Guarders {
            get {
                return guarders;
            }
            set {
                guarders = value;
                OnPropertyChanged("Guarders");
            }
        }

        private LogGuarder guarder;

        public LogGuarder Guarder {
            get {
                return guarder;
            }
            set {
                guarder = value;
                OnPropertyChanged("Guarder");
            }
        }

        const string auto_keyname = "xiaorsProcessGuarder";
        
        public XiaorsGuarder()
        {
            InitializeComponent();

            System.Diagnostics.Process process = System.Diagnostics.Process.GetCurrentProcess();
            SystemTool.closeSelf(process);

            this.DataContext = this;
        }
        
        private void NotifyIcon_Click(object sender, EventArgs e)
        {
            this.Show();
            //this.Visibility = Visibility.Visible;
            //this.ShowInTaskbar = true;
            this.Activate();
        }

        private void MenuItem_Checked(object sender, RoutedEventArgs e)
        {
            bool setOK = (this.auto_start.IsChecked ?
                new Func<bool>(
                    () => 
                    {
                        return AutoStart.SetAutoRun(auto_keyname, Path.Combine( 
                    Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName),
                    Path.GetFileName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName)));
                    }) :
               new Func<bool>(() => { return AutoStart.EraseAutoRun(auto_keyname); }))();
            
            this.auto_start.IsChecked = setOK ? true : false;
            if (!setOK)
            {
                System.Windows.MessageBox.Show("设置开机启动失败");
            }
        }

        private void hide_Click(object sender, RoutedEventArgs e)
        {
            this.Hide();
            //this.ShowInTaskbar = false;
            //this.Visibility = System.Windows.Visibility.Hidden;
        }

        private void quit_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.MessageBoxButton mbb = MessageBoxButton.OKCancel;
            System.Windows.MessageBoxResult result = System.Windows.MessageBox.Show("是否要停止所有任务并关闭程序","", mbb) ;
            switch (result)
            {
                case MessageBoxResult.Cancel:
                    return;
                case MessageBoxResult.No:
                    break;
                case MessageBoxResult.None:
                    break;
                case MessageBoxResult.OK:
                    StopAllTasks();
                    break;
                case MessageBoxResult.Yes:
                    break;
                default:
                    break;
            }
            System.Windows.Application.Current.Shutdown();
        }
        
        private void delete_item_click(object sender, RoutedEventArgs e)
        {
            var obj = (System.Windows.Controls.MenuItem)e.Source;
            var parent = (System.Windows.Controls.ContextMenu)obj.Parent;
            RadGridView dv = (RadGridView)parent.PlacementTarget;
            //var g = (LogGuarder)dg.CurrentItem;
            var g = (LogGuarder)dv.SelectedItem;
            if (g == null)
            {
                return;
            }
            else if(g.isRunning)
            {
                System.Windows.MessageBoxButton mbb = MessageBoxButton.OKCancel;
                System.Windows.MessageBoxResult result = System.Windows.MessageBox.Show("是否要停止并删除该任务？", "", mbb);
                switch (result)
                {
                    case MessageBoxResult.Cancel:
                        return;
                    case MessageBoxResult.OK:
                        //
                        g.Stop();
                        Guarders.Remove(g);
                        break;
                }
            }
            else
            {
                guarders.Remove(g);
            }
            
        }
        
        private void add_item_click(object sender, RoutedEventArgs e)
        {
            Guarders.Add(new LogGuarder() { Name="新建任务"});
        }

        private void Do_Click(object sender, RoutedEventArgs e)
        {
            LogGuarder item = (LogGuarder)tasksList.SelectedItem;
            if (item.isRunning)
            {
                item.isRunning = false;
                item.Stop();
            }
            else
            {
                if (checkCanStart(item))
                {
                    item.isRunning = true;
                    item.Start();
                }
                else
                {
                    System.Windows.MessageBox.Show("程序路径有误！");

                }
            }
        }

        private bool checkCanStart(LogGuarder item) {
            return !string.IsNullOrEmpty(item.AppPath) && File.Exists(item.AppPath);
        }

        private void save_btn_Click(object sender, RoutedEventArgs e)
        {
            StopAllTasks();
            if (guarders.SaveGuardsData())
            {
                MessageBoxResult result = System.Windows.MessageBox.Show("保存成功");
            }
            else
            {
                MessageBoxResult result = System.Windows.MessageBox.Show("保存失败");
            }
        }

        private void app_path_btn_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "exe files(*.exe)|*.exe";
            openFileDialog.Title = "选择一个应用程序";
            DialogResult result = openFileDialog.ShowDialog();
            if (result == System.Windows.Forms.DialogResult.Cancel)
            {
                return;
            }
            Guarder.AppPath = openFileDialog.FileName;
        }

        private void log_path_btn_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "Log files(*.txt)|*.txt|(*.log)|*.log|All files (*.*)|*.*";
            openFileDialog.Title = "选择一个日志文件";
            DialogResult result = openFileDialog.ShowDialog();
            if (result == System.Windows.Forms.DialogResult.Cancel)
            {
                return;
            }
            Guarder.LogFilePath = openFileDialog.FileName;
        }
        
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Guarders = Guarders.GetSingleGuarders("guarder.dat");
            this.SetIcon();
            this.auto_start.IsChecked = AutoStart.IsAutoRun(auto_keyname);

            StartAllTasks();
        }

        private void SetIcon() {
            object icon;
            util.ResourceHelper.Instance.Pg_Resources.TryGetValue("PerfCenterCpl", out icon);
            this.Icon = (ImageSource)icon;
            this.notifyIcon = new NotifyIcon();
            this.notifyIcon.Icon = NewProcessGuarder.Properties.Resources.PerfCenterCpl;
            this.notifyIcon.Visible = true;
            this.notifyIcon.Click += NotifyIcon_Click;
        }

        private void StartAllTasks()
        {
            if (Guarders != null && Guarders.Count > 0)
            {
                foreach (var item in Guarders)
                {
                    if (checkCanStart(item))
                    {
                        item.isRunning = true;
                        item.Start();
                    }
                }
            }
        }

        private void StopAllTasks()
        {
            if (Guarders != null && Guarders.Count > 0)
            {
                foreach (var item in Guarders)
                {
                    if (item.isRunning && File.Exists(item.AppPath))
                    {
                        item.isRunning = false;
                        item.Stop();
                    }
                }
            }
        }

    }
}

///// <summary>
///// 图片资源加载
///// </summary>
///// <param name="path"></param>
///// <returns></returns>
//public static BitmapImage GetBitmapImage(string path)
//{
//    BitmapImage bitmap = new BitmapImage();
//    bitmap.BeginInit();
//    bitmap.StreamSource = new MemoryStream(File.ReadAllBytes(path));
//    bitmap.EndInit();
//    bitmap.Freeze();
//    return bitmap;
//}
